﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Data;
using UFC.Common;
using UFC.DBUtility;

namespace MESQualityHistoryRecord
{
    /// <summary>
    /// MES质量数据包推送给QMS（pdf）
    /// 1.排故卡、2.质量卡、3.串件单
    /// </summary>
    public class SendQualityPackageToQms
    {
        private static string HostUrl = "http://localhost/InSiteWebApplication/";
        private static string RecordType = "QMS_SendQualityPackageToQms";

        public void RunQualityPackage()
        {
            //SendDealFaultBillPdf();//排故单打印文件
            //SendExchangeBillPdf();//串件单打印文件
            SendContainerWarrantyPdf();//质保单打印文件
        }
        /// <summary>
        /// 排故单打印文件
        /// </summary>
        private void SendDealFaultBillPdf()
        {
            var strSql = @"select d.engineno,d.productname,d.productbatchno,d.dealfaultbillname,d.dealfaultbillid 
                from dealfaultbill d 
                left join writetoothersystem w on w.parentid =d.dealfaultbillid and w.recordtype ='{0}'
                where d.isuse =0 and d.transferstatus ='7' and w.parentid is null
                and d.createdate>=to_date('2023-12-28','yyyy-MM-dd')";
            DataTable dt = OracleHelper.QueryTable(string.Format(strSql, RecordType), null);
            if (dt.Rows.Count > 0)
            {
                foreach (DataRow row in dt.Rows)
                {
                    var engineno = string.IsNullOrWhiteSpace(row["engineno"].ToString()) ? "~" : row["engineno"].ToString();
                    var productname = string.IsNullOrWhiteSpace(row["productname"].ToString()) ? "~" : row["productname"].ToString();
                    var productbatchno = string.IsNullOrWhiteSpace(row["productbatchno"].ToString()) ? "~" : row["productbatchno"].ToString();
                    var dealfaultbillname = string.IsNullOrWhiteSpace(row["dealfaultbillname"].ToString()) ? "~" : row["dealfaultbillname"].ToString();
                    var printUrl = HostUrl + "forms/Custom/ZS/DealFault/DealFaultBillPrintForm.aspx?PGDID=" + row["dealfaultbillid"]+"type=0";
                    var file = SavePrintHtmlToPdf(printUrl, DateTime.Now.ToString("yyyyMMddhhmmss"));//获取文件地址路径
                    if (file != null)
                    {
                        SendPdfFileToQms(file, "排故卡", engineno, productname, productbatchno, dealfaultbillname, row["dealfaultbillid"].ToString());
                    }
                }
            }
            else
            {
                LogHelp.WriteLog("质量数据包--暂无【排故卡】信息需要推送");
            }
        }
        /// <summary>
        /// 串件单打印文件
        /// </summary>
        private void SendExchangeBillPdf() {
            var strSql = @"select e.machine,p2.productname,e.containerno,e.exchangename,e.exchangeid,e.isarmy,e.customername
                        from exchangebill e 
                        left join product p on p.productid =e.productid 
                        left join productbase p2 on p2.productbaseid =p.productbaseid 
                        left join writetoothersystem w on w.parentid =e.exchangeid and w.recordtype ='{0}'
                        where e.billtype ='串件单' and e.billstatus ='2' and e.isuse =0 and w.parentid is null
                        and e.createdate>=to_date('2023-12-28','yyyy-MM-dd')";
            DataTable dt = OracleHelper.QueryTable(string.Format(strSql, RecordType), null);
            if (dt.Rows.Count > 0)
            {
                foreach (DataRow row in dt.Rows)
                {
                    if (row["isarmy"].ToString().Equals("1") && string.IsNullOrWhiteSpace(row["customername"].ToString())) { continue; }//提交QMS的必须有顾客代表返回信息
                    var engineno = string.IsNullOrWhiteSpace(row["machine"].ToString()) ? "~" : row["machine"].ToString();
                    var productname = string.IsNullOrWhiteSpace(row["productname"].ToString()) ? "~" : row["productname"].ToString();
                    var productbatchno = string.IsNullOrWhiteSpace(row["containerno"].ToString()) ? "~" : row["containerno"].ToString();
                    var exchangename = string.IsNullOrWhiteSpace(row["exchangename"].ToString()) ? "~" : row["exchangename"].ToString();
                    var printUrl = HostUrl + "forms/Custom/ZS/ExchangeInfoPrint.html?ExchangeID=" + row["exchangeid"];
                    var file = SavePrintHtmlToPdf(printUrl, DateTime.Now.ToString("yyyyMMddhhmmss"));//获取文件地址路径
                    if (file != null)
                    {
                        SendPdfFileToQms(file, "串件单", engineno, productname, productbatchno, exchangename, row["exchangeid"].ToString());
                    }
                }
            }
            else
            {
                LogHelp.WriteLog("质量数据包--暂无【串件单】信息需要推送");
            }
        }
        /// <summary>
        /// 质保单打印文件
        /// </summary>
        private void SendContainerWarrantyPdf() 
        {
            try
            {
                var strSql = @"select '' engineno,cci.productname,cci.containername,cci.realcontainerno containerno,cci.containertype,cq.id,cci.containerid,cci.workflowid,cci.factoryname,u.attributevalue factorycode
                from containercurrentinfo cci
                left join containerqualityensure cq on cq.containerid=cci.containerid
                left join writetoothersystem w on w.parentid =cq.id and w.recordtype ='{0}'
                left join userattribute u on u.parentid =cci.factoryid and u.userattributename ='分厂代码'
                where cq.status =1 and cq.checkconfirmemployee is not null and w.parentid is null
                order by cci.originalstartdate desc";
                DataTable dt = OracleHelper.QueryTable(string.Format(strSql, RecordType), null);
                if (dt.Rows.Count > 0)
                {
                    foreach (DataRow row in dt.Rows)
                    {
                        var engineno = string.IsNullOrWhiteSpace(row["engineno"].ToString()) ? "~" : row["engineno"].ToString();
                        var productname = string.IsNullOrWhiteSpace(row["productname"].ToString()) ? "~" : row["productname"].ToString();
                        var productbatchno = string.IsNullOrWhiteSpace(row["containerno"].ToString()) ? "~" : row["containerno"].ToString();
                        var dealfaultbillname = string.IsNullOrWhiteSpace(row["containername"].ToString()) ? "~" : row["containername"].ToString();
                        var printUrl = HostUrl + "forms/Custom/ContainerWarrantyPrintPopupForm.aspx?containerID=" + row["containerid"] + "&workflowID=" + row["workflowid"] + "&factoryname=" + row["factoryname"] + "&factorycode=" + row["factorycode"];
                        var file = SavePrintHtmlToPdf(printUrl, DateTime.Now.ToString("yyyyMMddhhmmss"));//获取文件地址路径
                        var childbatchno = string.Empty;//子序号批次
                        if (row["containertype"].ToString().Equals("3"))//批量带子序号批次 
                        {
                            var cbatchno= OracleHelper.GetSingle(string.Format("select listagg(c.containername,',') within group(order by c.parentcontainerid) childbatchno from container c where c.parentcontainerid ='{0}'", row["containerid"]));
                            if (cbatchno != null) { childbatchno = cbatchno.ToString(); }
                        }
                        //根据containerid关联3.166主子工艺流水卡映射信息表判断是否是--子工艺批次
                        DataTable fatherContainer = OracleHelper.QueryTable(string.Format(@"select c2.containername from containersubcontainer c 
                            left join containercurrentinfo c2 on c2.containerid =c.containerid where c.subcontainerid='{0}'", row["containerid"]),null);
                        if (fatherContainer.Rows.Count>0) 
                        {
                            //子工艺批次的（件号、批次号）取主卡的更换
                            productname = fatherContainer.Rows[0]["containername"].ToString().Split('/')[0];
                            productbatchno = fatherContainer.Rows[0]["containername"].ToString().Split('/')[1];
                        }
                        if (file != null)
                        {
                            SendPdfFileToQms(file, "质保单", engineno, productname, productbatchno, dealfaultbillname, row["id"].ToString(), childbatchno);
                        }
                    }
                }
                else
                {
                    LogHelp.WriteLog("质量数据包--暂无【质保单】信息需要推送");
                }
            }catch(Exception ex){
                LogHelp.WriteLog("质量数据包--【质保单】推送异常："+ex.Message);
            }
        }

        /// <summary>
        /// 调用QMS pdf文件上传接口
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="fileName"></param>
        /// <param name="engineNo"></param>
        /// <param name="partNo"></param>
        /// <param name="batchNo"></param>
        /// <param name="serialNo"></param>
        private void SendPdfFileToQms(string filePath, string typeName, string engineNo, string partNo, string batchNo, string serialNo, string id, string childBatchNo="")
        {
            string msg = string.Empty;
            var fileName = string.Empty;
            var uuid=Guid.NewGuid().ToString().Replace("-", "");
            try
            {
                byte[] fileBY = File.ReadAllBytes(filePath);//文件字节数组
                fileName = typeName +"-"+ engineNo + "-" + partNo + "-" + batchNo.Replace("/","-")+".pdf";
                //调用QMS接口
                QmsFileAPI.MesBbomFileService qmsFile = new QmsFileAPI.MesBbomFileService();
                if (!string.IsNullOrWhiteSpace(childBatchNo))//批量带子序号的批次
                {
                    foreach (string childbatchNo in childBatchNo.Split(',')) 
                    {
                        fileName = typeName + "-" + engineNo + "-" + partNo + "-" + childbatchNo.Replace("/", "-") + ".pdf";
                        msg = qmsFile.receiveMesFileData(typeName, fileName, engineNo.Equals("~") ? "" : engineNo, partNo, childbatchNo, fileBY, uuid);
                        LogHelp.WriteLog("质量数据包--子批次号：" + partNo + "/" + childbatchNo + "--" + fileName + "调用QMS返回:" + msg);
                    }
                }
                else {
                    msg = qmsFile.receiveMesFileData(typeName, fileName, engineNo.Equals("~") ? "" : engineNo, partNo, batchNo, fileBY, uuid);
                    LogHelp.WriteLog("质量数据包--批次号：" + partNo + "/" + batchNo +"--"+ fileName + "调用QMS返回:" + msg);
                }
            }catch(Exception ex){
                msg = ex.Message;
            }
            Dictionary<string, string> recordPara = new Dictionary<string, string>() { //string.IsNullOrWhiteSpace(msg)?null:msg
                        {"ParentId",id},{"RecordType",RecordType},
                        {"ContainerID",uuid},{"ContainerName",typeName},
                        {"ProductName",partNo},{"WorkflowStepName",null},
                        {"SendXml","<?xml version=\"1.0\" encoding=\"UTF-8\"?><RespMsg>"+fileName+"--"+serialNo+"</RespMsg>"},
                        {"ResXml","<?xml version=\"1.0\" encoding=\"UTF-8\"?><RespMsg>"+msg+"</RespMsg>"},
                        {"IsSuccess",(msg.ToString().Contains("SUCCESS")?"1":"0")}
                    };
            OracleDAL.InserOtherSystemRecord(recordPara);
            deleteDpf(filePath);
//            try
//            {
//                string strSql = @"insert into WritetoOtherSystem wo (wo.containerid,wo.containername,wo.createdate,wo.issuccess,wo.parentid,wo.productname,
//                wo.recordtype,wo.sendxml,wo.resxml,wo.workflowstepname,wo.writetoothersystemid) values ('{0}','{1}',sysdate,{2},'{3}','{4}',
//                '{5}','{6}','{7}','{8}',sys_guid())";
//                strSql = string.Format(strSql, null, typeName, (msg.ToString().Contains("SUCCESS") ? "1" : "0"), id, partNo, RecordType, fileName, msg, null);

//                OracleHelper.ExecuteSql(strSql);
//            }catch(Exception ex){
//                LogHelp.WriteLog("质量数据包--"+fileName + "存入数据库失败:" + ex.Message);
//            }
        }


        /// <summary>
        /// 打印页面另存为pdf
        /// </summary>
        /// <param name="url">打印路径</param>
        /// <param name="fileName">文件名称</param>
        /// <returns>返回pdf保存路径</returns>
        private string SavePrintHtmlToPdf(string url, string fileName)
        {
            try
            {
                var path = AppDomain.CurrentDomain.BaseDirectory + "\\" + DateTime.Now.ToString("yyyyMMdd");
                var path2 = AppDomain.CurrentDomain.BaseDirectory + "\\" + DateTime.Now.AddDays(-1).ToString("yyyyMMdd");
                if(!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                if(Directory.Exists(path2))//删除上一天的文件夹，避免增大存储
                {
                    Directory.Delete(path2);
                }
                var filePath = path +"\\"+ fileName + @".pdf";
                var pdf = new NReco.PdfGenerator.HtmlToPdfConverter();
                pdf.GeneratePdfFromFile(url, null, filePath);//
                if (File.Exists(filePath))
                {

                    return filePath;
                }
                return null;
            }
            catch (Exception ex)
            {
                LogHelp.WriteLog(fileName + "生成pdf文件失败:" + ex.Message);
                return null;
            }
        }
        /// <summary>
        /// 根据路径删除pdf
        /// </summary>
        /// <param name="filePath"></param>
        private void deleteDpf(string filePath)
        {
            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }
        }

    }
}
